<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="50%">
      <el-form
        status-icon
        :rules="rules"
        ref="ruleForm"
        class="demo-ruleForm form"
        label-width="100px"
        :model="form"
        v-loading="loading"
      >
        <el-form-item class="item" label="用户名:" prop="userName">
          <el-input
            :disabled="type == 'edit'"
            v-model="form.userName"
            placeholder="请输入用户名"
          ></el-input>
        </el-form-item>
        <el-form-item class="item" label="部门:" prop="department">
          <el-input
            v-model="form.department"
            placeholder="请输入部门"
          ></el-input>
        </el-form-item>
        <el-form-item class="item" label="角色:" prop="userRole">
          <el-select
            style="width: 100%"
            v-model="form.userRole"
            placeholder="请选择角色"
          >
            <el-option
              v-for="item in data"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="item" label="真实姓名:" prop="realName">
          <el-input
            :disabled="type == 'edit'"
            v-model="form.realName"
            placeholder="请输入真实姓名"
          ></el-input>
        </el-form-item>

        <el-form-item class="item" label="电子邮件:" prop="userMail">
          <el-input
            v-model="form.userMail"
            placeholder="请输入电子邮件"
          ></el-input>
        </el-form-item>
        <el-form-item class="item" label="手机号:" prop="phoneNumber">
          <el-input
            style="width: 100%"
            v-model="form.phoneNumber"
            placeholder="请输入手机号"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel" class="loginBth2">取 消</el-button>
        <el-button
          type="primary"
          @click="submit"
          :loading="loading"
          class="loginBth"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addUser, getUserDetail, editUser } from "@/common/api";
export default {
  name: "AddAccount",
  props: {
    data: Array,
  },
  components: {},
  computed: {
    title() {
      return this.type == "add" ? "新增账号" : "编辑账号";
    },
  },
  data() {
    var checkEmail = (rule, value, cb) => {
      if (!value) return cb();
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的邮箱！"));
    };

    var checkMobile = (rule, value, cb) => {
      if (!value) return cb();
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("请输入合法的手机号！"));
    };

    return {
      dialogFormVisible: false,
      options: [],
      form: {
        department: "",
        phoneNumber: "",
        realName: "",
        userMail: "",
        userName: "",
        userRole: "",
      },
      rules: {
        userName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        userRole: [{ required: true, message: "请选择角色", trigger: "blur" }],
        realName: [
          { required: true, message: "请输入真实姓名", trigger: "blur" },
        ],
        userMail: [{ validator: checkEmail, trigger: "blur" }],
        phoneNumber: [{ validator: checkMobile, trigger: "blur" }],
      },
      loading: false,
      type: "add",
      id: "",
    };
  },
  mounted() {},
  created() {},
  methods: {
    getDetail(id) {
      this.$refs["ruleForm"]?.resetFields(); //打开dialog时重置校验
      this.loading = true;
      this.id = id;
      getUserDetail({ id })
        .then((res) => {
          this.loading = false;
          if (res.success) {
            for (let key in this.form) {
              this.form[key] = res.data[key];
            }
          } else {
            this.$errorMsg(res.message);
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    submit() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          if (this.type == "add") {
            this.loading = true;
            addUser(this.form)
              .then((res) => {
                this.loading = false;
                if (res.success) {
                  this.$successMsg("添加成功");
                  this.dialogFormVisible = false;
                  let arr = Object.keys(this.form);
                  arr.forEach((i) => (this.form[i] = "")); //表单数据置空
                  this.$emit("getTable");
                } else {
                  this.$errorMsg(res.message);
                }
              })
              .catch((err) => {
                this.loading = false;
              });
          } else {
            editUser({ ...this.form, id: this.id })
              .then((res) => {
                this.loading = false;
                if (res.success) {
                  this.$successMsg("修改成功");
                  this.dialogFormVisible = false;
                  let arr = Object.keys(this.form);
                  arr.forEach((i) => (this.form[i] = "")); //表单数据置空
                  this.$emit("getTable");
                } else {
                  this.$errorMsg(res.message);
                }
              })
              .catch((err) => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    cancel() {
      this.dialogFormVisible = false;
      let arr = Object.keys(this.form);
      arr.forEach((i) => (this.form[i] = "")); //表单数据置空
    },
  },
};
</script>


<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  //   gap: 20px;
  .item {
    width: 50%;
  }
}
</style>